<template>
  <view class="container">
    <!-- 用户信息 -->
    <view
      v-if="isAuthInfo"
      class="userinfo"
    >
      <view class="userinfo-con">
        <view class="userinfo-avatar" @tap="openEditUserInfo">
          <image
            :src="userInfo.pic ? userInfo.pic : '/static/images/icon/head04.png'"
          />
        </view>
        <view class="userinfo-name">
          <view>{{ userInfo.nickName ? userInfo.nickName : "用户昵称" }}</view>
        </view>
      </view>
    </view>

    <view
      v-if="!isAuthInfo"
      class="userinfo-none"
    >
      <view
        class="default-pic"
        @tap="toLogin"
      >
        <image src="@/static/images/icon/head04.png" />
      </view>
      <view
        class="none-login"
        @tap="toLogin"
      >
        <button class="unlogin">
          未登录
        </button>
        <button class="click-login">
          点击登录账号
        </button>
      </view>
    </view>
    <!-- end 用户信息 -->

    <view class="list-cont">
      <!-- 订单状态 -->
      <view class="total-order">
        <view class="order-tit">
          <text style="font-weight:bold">
            我的订单
          </text>
          <view
            class="checkmore"
            data-sts="0"
            @tap="toOrderListPage"
          >
            <text>查看全部</text>
            <text class="arrowhead" />
          </view>
        </view>
        <view class="procedure">
          <view
            class="items"
            data-sts="1"
            @tap="toOrderListPage"
          >
            <image src="@/static/images/icon/toPay.png" />
            <text>待支付</text>
            <text
              v-if="orderAmount.unPay>0"
              class="num-badge"
            >
              {{ orderAmount.unPay }}
            </text>
          </view>
          <view
            class="items"
            data-sts="2"
            @tap="toOrderListPage"
          >
            <image src="@/static/images/icon/toDelivery.png" />
            <text>待发货</text>
            <text
              v-if="orderAmount.payed>0"
              class="num-badge"
            >
              {{ orderAmount.payed }}
            </text>
          </view>
          <view
            class="items"
            data-sts="3"
            @tap="toOrderListPage"
          >
            <image src="@/static/images/icon/toTake.png" />
            <text>待收货</text>
            <text
              v-if="orderAmount.consignment>0"
              class="num-badge"
            >
              {{ orderAmount.consignment }}
            </text>
          </view>
          <view
            class="items"
            data-sts="5"
            @tap="toOrderListPage"
          >
            <image src="@/static/images/icon/toComment.png" />
            <text>已完成</text>
          </view>
        </view>
      </view>
      <!--end 订单状态 -->



      <view class="my-menu">
        <view
          class="memu-item"
          @tap="toAddressList"
        >
          <view class="i-name">
            <image src="@/static/images/icon/myAddr.png" />
            <text>收货地址</text>
          </view>
          <view class="arrowhead" />
        </view>

        <view
          class="memu-item"
          @tap="myCollectionHandle"
        >
          <view class="i-name">
            <image src="@/static/images/icon/promotion.png" />
            <text>我的收藏</text>
          </view>
          <view class="arrowhead" />
        </view>
      </view>

      <!--end 列表项 -->

      <view
        v-if="isAuthInfo"
        class="log-out"
        @tap="logout"
      >
        <view class="log-out-n">
          <text>退出登录</text>
        </view>
      </view>
    </view>

    <!-- 编辑弹窗 -->
    <view v-if="showEdit" class="edit-popup-mask">
      <view class="edit-popup-card">
        <view class="edit-title">修改个人信息</view>
        <view class="edit-row">
          <text class="edit-label">昵称：</text>
          <input v-model="editNickName" class="edit-input" placeholder="请输入昵称" />
        </view>
        <view class="edit-row">
          <text class="edit-label">头像：</text>
          <image
            v-if="editAvatarUrl"
            :src="editAvatarUrl"
            class="edit-avatar"
          />
          <button class="edit-btn" @tap="chooseAvatar">选择图片</button>
        </view>
        <view class="edit-row">
          <text class="edit-label">邮箱：</text>
          <input v-model="editEmail" class="edit-input" placeholder="请输入邮箱" />
        </view>
        <view class="edit-row">
          <text class="edit-label">手机号：</text>
          <input v-model="editMobile" class="edit-input" placeholder="请输入手机号" />
        </view>
        <view class="edit-row">
          <text class="edit-label">性别：</text>
          <label class="edit-radio">
            <input type="radio" :value="'1'" v-model="editGender" /> 男
          </label>
          <label class="edit-radio">
            <input type="radio" :value="'2'" v-model="editGender" /> 女
          </label>
          <label class="edit-radio">
            <input type="radio" :value="'0'" v-model="editGender" /> 保密
          </label>
        </view>
        <view class="edit-actions">
          <button class="edit-btn save" @tap="submitEdit">保存</button>
          <button class="edit-btn cancel" @tap="closeEditUserInfo">取消</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
const picDomain = import.meta.env.VITE_APP_RESOURCES_URL
const baseApi = import.meta.env.VITE_APP_BASE_API

const isAuthInfo = ref(false)
const userInfo = ref({})
const orderAmount = ref('')
const collectionCount = ref(0)
const showEdit = ref(false)

/**
 * 生命周期函数--监听页面显示
 */
onShow(() => {
  // 获取用户信息
  http.request({
    url: '/p/user/userInfo',
    method: 'GET'
  }).then(res => {
    if (res.code === '00000' && res.data) {
      userInfo.value = res.data
      isAuthInfo.value = true
    } else {
      isAuthInfo.value = false
      userInfo.value = {}
    }
  })

  // 加载订单数字
  if (isAuthInfo.value) {
    uni.showLoading()
    http.request({
      url: '/p/myOrder/orderCount',
      method: 'GET',
      data: {}
    })
      .then(({ data }) => {
        uni.hideLoading()
        orderAmount.value = data
      })
    showCollectionCount()
  }
})

const toAddressList = () => {
  uni.navigateTo({
    url: '/pages/delivery-address/delivery-address'
  })
}

const toOrderListPage = (e) => {
  if (!isAuthInfo.value) {
    uni.navigateTo({
      url: '/pages/accountLogin/accountLogin'
    })
    return
  }
  const sts = e.currentTarget.dataset.sts
  uni.navigateTo({
    url: `/pages/orderList/orderList${sts ? '?sts=' + sts : ''}`
  })
}

/**
 * 查询所有的收藏量
 */
const showCollectionCount = () => {
  uni.showLoading()
  http.request({
    url: '/p/user/collection/count',
    method: 'GET',
    data: {}
  })
    .then(({ data }) => {
      uni.hideLoading()
      collectionCount.value = data
    })
}

/**
 * 我的收藏跳转
 */
const myCollectionHandle = () => {
  let url = '/pages/prod-classify/prod-classify?sts=5'
  const id = 0
  const title = '我的收藏商品'
  if (id) {
    url += '&tagid=' + id + '&title=' + title
  }
  uni.navigateTo({
    url
  })
}

/**
 * 去登陆
 */
const toLogin = () => {
  uni.navigateTo({
    url: '/pages/accountLogin/accountLogin'
  })
}

/**
 * 退出登录
 */
const logout = () => {
  http.request({
    url: '/logOut',
    method: 'post'
  })
    .then(() => {
      util.removeTabBadge()
      uni.removeStorageSync('loginResult')
      uni.removeStorageSync('token')
      uni.showToast({
        title: '退出成功',
        icon: 'none'
      })
      orderAmount.value = ''
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/index/index'
        })
      }, 1000)
    })
}

const editNickName = ref('')
const editAvatarUrl = ref('')
const editEmail = ref('')
const editMobile = ref('')
const editGender = ref('0') // 必须是字符串
const loginResult = ref(uni.getStorageSync('loginResult'))
const token = loginResult.accessToken

function openEditUserInfo() {
  editNickName.value = userInfo.value.nickName || ''
  editAvatarUrl.value = userInfo.value.pic || ''
  editEmail.value = userInfo.value.email || ''
  editMobile.value = userInfo.value.userMobile || ''
  // 性别映射，全部转字符串
  let sex = (userInfo.value.sex || '').toString().toUpperCase();
  if (sex === 'M' || sex === '1') {
    editGender.value = '1'
  } else if (sex === 'F' || sex === '2') {
    editGender.value = '2'
  } else {
    editGender.value = '0'
  }
  showEdit.value = true
}
function closeEditUserInfo() {
  showEdit.value = false
}

// 选择头像
function chooseAvatar() {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      const token = uni.getStorageSync('accessToken')
      if (!token) {
        uni.showToast({ title: '请先登录', icon: 'none' })
        return
      }
      uni.uploadFile({
        url: `${baseApi}/p/social/post/upload`,
        filePath: res.tempFilePaths[0],
        name: 'file',
        header: {
          'Authorization': token
        },
        success: (uploadRes) => {
          let data = {}
          try {
            data = JSON.parse(uploadRes.data)
          } catch (e) {
            uni.showToast({ title: '上传失败', icon: 'none' })
            return
          }
          if (uploadRes.statusCode === 401) {
            uni.removeStorageSync('accessToken')
            uni.showModal({
              title: '提示',
              content: '登录已过期，请重新登录',
              confirmText: '去登录',
              success: (res) => {
                if (res.confirm) {
                  uni.navigateTo({
                    url: '/pages/accountLogin/accountLogin'
                  })
                }
              }
            })
            return
          }
          if (uploadRes.statusCode !== 200 || data.code !== '00000') {
            uni.showToast({ title: data.msg || '上传失败', icon: 'none' })
            return
          }
          editAvatarUrl.value = data.data
          uni.showToast({ title: '上传成功', icon: 'success' })
        },
        fail: () => {
          uni.showToast({ title: '上传失败', icon: 'none' })
        }
      })
    }
  })
}

// 提交修改
function submitEdit() {
  let genderValue = editGender.value;
  // 如果后端需要字符串
  if (genderValue === '1') genderValue = 'M';
  else if (genderValue === '2') genderValue = 'F';
  else genderValue = '0';

  http.request({
    url: '/p/user/setUserInfo',
    method: 'PUT',
    data: {
      nickName: editNickName.value,
      avatarUrl: editAvatarUrl.value,
      email: editEmail.value,
      userMobile: editMobile.value,
      gender: genderValue
    }
  }).then(res => {
    if (res.code === '00000') {
      uni.showToast({ title: '修改成功', icon: 'none' })
      showEdit.value = false
      onShow()
    } else {
      uni.showToast({ title: res.msg || '修改失败', icon: 'none' })
    }
  })
}
</script>

<style scoped lang="scss">
@use './user.scss';

.edit-popup-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.3);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.edit-popup-card {
  background: #fff;
  border-radius: 12px;
  padding: 32px 24px 20px 24px;
  min-width: 300px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.12);
  display: flex;
  flex-direction: column;
  align-items: center;
}
.edit-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 18px;
}
.edit-row {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
.edit-label {
  width: 48px;
  text-align: right;
  margin-right: 8px;
  color: #333;
}
.edit-input {
  flex: 1;
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 6px 10px;
  font-size: 15px;
}
.edit-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-right: 10px;
  border: 1px solid #eee;
  object-fit: cover;
}
.edit-actions {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
.edit-btn {
  flex: 1;
  margin: 0 6px;
  padding: 8px 0;
  border-radius: 6px;
  font-size: 15px;
  background: #f5f5f5;
  color: #333;
  border: none;
}
.edit-btn.save {
  background: #1b7dec;
  color: #fff;
}
.edit-btn.cancel {
  background: #eee;
  color: #666;
}
.edit-radio {
  margin-right: 16px;
  font-size: 15px;
  display: flex;
  align-items: center;
}
.edit-radio input[type='radio'] {
  margin-right: 4px;
}
</style>
